package codeTop;

import java.util.*;

public class q40 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<int[]> nums = new ArrayList<>();
        for (int i = 0; i < candidates.length; i++) {
            if (nums.size()>0&&nums.get(nums.size()-1)[0]==candidates[i]){
                nums.get(nums.size()-1)[1]++;
            }else {
                nums.add(new int[]{candidates[i],1});
            }
        }
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        dfs(res,list,target,0,nums);
        return res;
    }

    private void dfs(List<List<Integer>> res, List<Integer> list, int target,int idx,List<int[]> map) {
        if (target == 0) {
            res.add(List.copyOf(list));
            return;
        }
        if (idx == map.size()) {
            return;
        }
        if (target<map.get(idx)[0]){
            return;
        }
        //不要
        dfs(res,list,target,idx+1,map);
        //要
        for (int i = 1; map.get(idx)[0]*i<=target&&i<=map.get(idx)[1]; i++) {
            list.add(map.get(idx)[0]);
            dfs(res,list,target-i*map.get(idx)[0],idx+1,map);
        }
        for (int i = 1; map.get(idx)[0]*i<=target&&i<=map.get(idx)[1]; i++) {
            list.remove(list.size()-1);
        }
    }

    public static void main(String[] args) {
        int[] candidates = new int[]{10,1,2,7,6,1,5};
        q40 q = new q40();
        q.combinationSum2(candidates,8);
    }
}
